/**
 * The app navigator (formerly "AppNavigator" and "MainNavigator") is used for the primary
 * navigation flows of your app.
 * Generally speaking, it will contain an auth flow (registration, login, forgot password)
 * and a "main" flow which the user will use once logged in.
 */
import { DarkTheme, DefaultTheme, NavigationContainer } from "@react-navigation/native"
import { createNativeStackNavigator, NativeStackScreenProps } from "@react-navigation/native-stack"
import { observer } from "mobx-react-lite"
import React, { useEffect, useState } from "react"
import { useColorScheme } from "react-native"
import * as Screens from "app/screens"
import Config from "../config"
import { navigationRef, useBackButtonHandler } from "./navigationUtilities"
import { colors } from "app/theme"
import BottomTabNavigator from "./BottomTabNavigator"
import Login from "app/screens/Login"
import { useAppDispatch, useAppSelector } from "app/redux/hooks"
import { setLogin } from "app/redux/slices/authSlice"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { getEtheraProvider } from "app/services/apis/provider"
import { setProviderInfo } from "app/redux/slices/providerSlice"

export type AppStackParamList = {
  Login: undefined
  Welcome: undefined
  AddAppointment: undefined
  AppointmentDetails: undefined
  EditAddAppointment: undefined
  EditAppointmentDetails: undefined
}

const exitRoutes = Config.exitRoutes

export type AppStackScreenProps<T extends keyof AppStackParamList> = NativeStackScreenProps<
  AppStackParamList,
  T
>

// Documentation: https://reactnavigation.org/docs/stack-navigator/
const Stack = createNativeStackNavigator<AppStackParamList>()

const AppStack = observer(function AppStack() {
  return (
    <Stack.Navigator
      screenOptions={{ headerShown: false, navigationBarColor: colors.background }}
      initialRouteName="Welcome"
    >
      <Stack.Screen name="Welcome" component={BottomTabNavigator} />
      <Stack.Screen name="AddAppointment" component={Screens.AddAppointment} />
      <Stack.Screen name="AppointmentDetails" component={Screens.AppointmentDetails} />
      <Stack.Screen name="EditAppointmentDetails" component={Screens.EditAppointmentDetails} />
      <Stack.Screen name="EditAddAppointment" component={Screens.EditAddAppointment} />
    </Stack.Navigator>
  )
})

function Authstack() {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false, navigationBarColor: colors.background }}>
      <Stack.Screen name="Login" component={Login} />
    </Stack.Navigator>
  )
}

export interface NavigationProps
  extends Partial<React.ComponentProps<typeof NavigationContainer>> {}

export const AppNavigator = observer(function AppNavigator(props: NavigationProps) {
  const colorScheme = useColorScheme()

  useBackButtonHandler((routeName) => exitRoutes.includes(routeName))
  const [token, setToken] = useState("")
  const authSelector = useAppSelector((state) => state?.auth)
  const dispatch = useAppDispatch()

  useEffect(() => {
    if (!authSelector?.isLoggedIn) {
      checkUserLoginAction()
    } else {
      getProvider()

      setToken(authSelector?.userToken)
    }
  }, [authSelector?.isLoggedIn])

  const getProvider = () => {
    getEtheraProvider()
      .then((res: any) => {
        console.log("success in fetching provider details")
        dispatch(setProviderInfo(res?.data))
      })
      .catch((error: any) => {
        console.log("error in fetching provider details", error)
      })
  }

  const checkUserLoginAction = async () => {
    const token: any = await AsyncStorage.getItem("token")
    console.log("token", token)
    if (token) {
      dispatch(setLogin({ token: token, isLoggedIn: true }))
      getProvider()
    } else {
      setToken("")
    }
  }

  return (
    <NavigationContainer
      ref={navigationRef}
      theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
      {...props}
    >
      {/* <Authstack /> */}
      {token ? <AppStack /> : <Authstack />}

      {/* <AppStack /> */}
    </NavigationContainer>
  )
})
